package com.jrx.anytxn.reporting.job.xib.step;

import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.customer.entity.CmLimitChangeLog;
import com.jrx.anytxn.customer.mapper.ext.ExtCmLimitChangeLogMapper;
import com.jrx.anytxn.reporting.entity.CmInteCoLonCrdtInfo;
import com.jrx.anytxn.reporting.entity.CoLonCrdtInfoBean;
import com.jrx.anytxn.reporting.entity.LimitChangeLogUpdate;
import com.jrx.anytxn.reporting.mapper.base.CmInteCoLonCrdtInfoMapper;
import org.springframework.batch.item.ItemWriter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @comment: 贷款授信信息数据报表Writer
 * @author: hsoong
 * @date: 2021/7/2 10:04
 */
@Service
public class CreditInfoReportingWriter implements ItemWriter<CoLonCrdtInfoBean> {

    @Resource
    CmInteCoLonCrdtInfoMapper cmInteCoLonCrdtInfoMapper;

    @Resource
    ExtCmLimitChangeLogMapper extCmLimitChangeLogMapper;

    @Override
    public void write(List<? extends CoLonCrdtInfoBean> list) throws Exception {
        for (CoLonCrdtInfoBean item : list) {
            CmInteCoLonCrdtInfo crdtInfo = item.getCrdtInfo();
            cmInteCoLonCrdtInfoMapper.insertSelective(crdtInfo);

            LimitChangeLogUpdate updateLimitChangeLog = item.getUpdateLimitChangeLog();
            if (Objects.nonNull(updateLimitChangeLog)) {
                CmLimitChangeLog changeLog = BeanMapping.copy(updateLimitChangeLog, CmLimitChangeLog.class);
                List<CmLimitChangeLog> cmLimitChangeLogs = extCmLimitChangeLogMapper.queryAllByEtlContractNumber(changeLog.getTenantId(), changeLog.getEtlContractNumber(), changeLog.getCustomerId());
                cmLimitChangeLogs.stream().collect(Collectors.groupingBy(CmLimitChangeLog::getContractNumber,Collectors.maxBy(Comparator.comparing(CmLimitChangeLog::getExpiryDate)))).forEach((k,v)->{
                    if (v.isPresent()) {
                        changeLog.setId(v.get().getId());
                        extCmLimitChangeLogMapper.updateEtlExpiryDate(changeLog);
                    }
                });
            }
        }
    }

}
